<template>
  <div class="main">
    <vue-particles></vue-particles>
    <div class="login">
      <div class="login_avatar">
        <img src="../../assets/head.jpg" alt="">
      </div>
      <h2 class="title">用户登录</h2>
      <a-form-model ref="form" :model="model" :rules="validatorRules" class="login_form">
        <a-form-model-item required prop="username">
          <a-input v-model="model.username" size="large" placeholder="请输入帐户名">
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item required prop="password">
          <a-input v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入密码">
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-model-item>

        <a-form-item>
          <a-button type="primary" htmlType="submit" class="login-button" :loading="loginBtn"
                    ghost @click.stop.prevent="handleSubmit" :disabled="loginBtn">登陆
          </a-button>
          <a-button ghost class="login-button" @click="exit()">退出</a-button>
        </a-form-item>
      </a-form-model>
      <login-select-tenant ref="loginSelect" @success="loginSelectOk"></login-select-tenant>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN, ENCRYPTED_STRING } from '@/store/mutation-types'
import { mapActions } from 'vuex'

import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { getEncryptedString } from '@/utils/encryption/aesEncrypt'
import { timeFix } from '@/utils/util'
import LoginSelectTenant from '@views/user/LoginSelectTenant'
import ThirdLogin from '@views/user/third/ThirdLogin'
import { LoginByFace } from '@api/login'
import user from '@/store/modules/user'

export default {
  components: {
    LoginSelectTenant,
    TwoStepCaptcha,
    ThirdLogin
  },
  data() {
    return {
      model: {
        username: '',
        password: '',
        inputCode: ''
      },
      loginType: 0,
      validatorRules: {
        username: [
          { required: true, message: '请输入用户名!' },
          { validator: this.handleUsernameOrEmail }
        ],
        password: [{
          required: true, message: '请输入密码!', validator: 'click'
        }]
      },
      customActiveKey: 'tab1',
      requestCodeSuccess: false,
      randCodeImage: '',
      currdatetime: '',
      loginBtn: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,

      encryptedString: {
        key: '',
        iv: ''
      }
    }
  },
  created() {
    this.currdatetime = new Date().getTime()
    this.model.rememberMe = true
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
  },
  methods: {
    ...mapActions(['Login', 'Logout','LoginByFace']),
    handleTabClick(key) {
      this.customActiveKey = key
    },
    handleUsernameOrEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    /**跳转到登录页面的参数-账号获取*/
    getRouterData() {
      this.$nextTick(() => {
        let temp = this.$route.params.username || this.$route.query.username || ''
        if (temp) {
          this.model['username'] = temp
        }
      })
    },
    handleRememberMeChange(e) {
      this.model.rememberMe = e.target.checked
    },
    //登录
    handleSubmit() {
      let that = this
      let loginParams = {}
      that.loginBtn = true
      // 使用账户密码登录
      this.loginByUsername()

    },
    exit() {
      window.location.href = '/'
    },

    /**
     * 验证字段
     * @param arr
     * @param callback
     */
    validateFields(arr, callback) {
      let promiseArray = []
      for (let item of arr) {
        let p = new Promise((resolve, reject) => {
          this.$refs['form'].validateField(item, (err) => {
            if (!err) {
              resolve()
            } else {
              reject(err)
            }
          })
        })
        promiseArray.push(p)
      }
      Promise.all(promiseArray).then(() => {
        callback()
      }).catch(err => {
        callback(err)
      })
    },
    //账号密码登录
    loginByUsername() {
      this.validateFields(['username', 'password'], (err) => {
        if (!err) {
          let loginParams = {
            username: this.model.username,
            password: this.model.password,
          }
          this.LoginByFace(loginParams).then((res) => {
            user.state.userRole = res.result.userRole.str1
            localStorage.setItem("role",res.result.userRole.str1)
            this.$refs.loginSelect.show(res.result)
          }).catch((err) => {
            console.log('error:' + err)
            this.requestFailed(err)
          })
        } else {
          this.loginBtn = false
        }
      })
    },

    //登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试'
      this.$notification['error']({
        message: '登录失败',
        description: description,
        duration: 4
      })
      this.loginBtn = false
    },
    loginSelectOk() {
      this.loginSuccess()
    },
    //登录成功
    loginSuccess() {
      this.$router.push({ path: '/toolbox' })
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`
      })
    },
    cmsFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: err,
        duration: 4
      })
    },
    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    //获取密码加密规则
    getEncrypte() {
      var encryptedString = Vue.ls.get(ENCRYPTED_STRING)
      if (encryptedString == null) {
        getEncryptedString().then((data) => {
          this.encryptedString = data
        })
      } else {
        this.encryptedString = encryptedString
      }
    }

  }

}
</script>
<style lang="less" scoped>
.main {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

#particles-js {
  width: 100%;
  height: 100%;
  position: absolute;
  padding: 0;
  margin: 0;
  background-image: radial-gradient(#002953, #041222);
  background-size: 100% 100%;
}

.login {
  background-image: linear-gradient(#002953, #62388d);
  width: 400px;
  height: 300px;
  padding: 20px;
  position: relative;
  left: 0;
  right: 0;
  top: 30%;
  margin: auto;
  border-radius: 5%;
}

.login_form {
  margin-top: 20px;
  transform: translate(0px, -30px);
}

.title {
  position: absolute;
  top: 15%;
  left: 50%;
  transform: translate(-50%);
  color: white;
}

//头像
.login_avatar {
  height: 80px;
  width: 80px;
  border: antiquewhite 1px solid;
  border-radius: 50%;
  padding: 10px;
  box-shadow: 0 0 10px #ddd;
  position: relative;
  left: 50%;
  transform: translate(-50%, -80%);
  background-color: #fff;

  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    background-color: cornflowerblue;
    transition: all 2s
  }

  img:hover {
    transform: rotate(360deg);
  }
}

.login-button {
  width: 43%;
  height: 40px;
}

.ant-btn + .ant-btn {
  margin-left: 30px;
}
</style>
